package main

import (
	"flag"
	// "path/filepath"
	"time"

	"github.com/go-kratos/kratos/contrib/registry/etcd/v2"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/config/file"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/selector"
	"github.com/go-kratos/kratos/v2/selector/filter"
	"github.com/go-kratos/kratos/v2/selector/wrr"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/google/uuid"
	_ "go.uber.org/automaxprocs"

	"gitee.com/danqingzhao/go-dango/apps/user/conf"
	"gitee.com/danqingzhao/go-dango/apps/user/data"

	// "gitee.com/danqingzhao/go-dango/pkg/common"
	"gitee.com/danqingzhao/go-dango/pkg/proto/settings"
)

const AppName = "auth"

// go build -ldflags "-X main.Version=x.y.z"
var (
	// flagconf is the config flag.
	flagconf string
)

func init() {
	flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func newApp(loggers *settings.Loggers, gs *grpc.Server, hs *http.Server, d *data.Data) *kratos.App {
	return kratos.New(
		kratos.ID(uuid.NewString()),
		kratos.Name(AppName),
		kratos.Version(conf.Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(loggers.Server),
		kratos.Server(gs, hs),
		kratos.Registrar(etcd.New(d.Etcd)),
	)
}

func main() {
	flag.Parse()
	c := config.New(
		config.WithSource(
			file.NewSource(flagconf),
		),
	)
	defer c.Close()

	if err := c.Load(); err != nil {
		panic(err)
	}
	var bc conf.Bootstrap
	if err := c.Scan(&bc); err != nil {
		panic(err)
	}
	loggers := settings.NewLoggers(
		bc.Data.Logger,
		"ts", time.Now().Format(time.DateTime),
		"caller", log.DefaultCaller,
		"service.id", conf.ServiceID,
		"service.name", AppName,
		"service.version", conf.Version,
	)
	logHelpers := settings.NewLogHelpers(loggers)
	// if err := common.NewI18nLocalizer(filepath.Join(flagconf, "i18n")); err != nil {
	// 	logHelpers.Server.Error(err.Error())
	// 	panic(err)
	// }
	filter := filter.Version("2.0.0")
	selector.SetGlobalSelector(wrr.NewBuilder())
	app, cleanup, err := wireApp(bc.Server, bc.Data, bc.Security, loggers, logHelpers, filter)
	if err != nil {
		logHelpers.Server.Error(err.Error())
		panic(err)
	}
	defer cleanup()

	// start and wait for stop signal
	if err := app.Run(); err != nil {
		logHelpers.Server.Error(err.Error())
		panic(err)
	}
}
